#!/bin/bash

if [ -n "$1" ] ; then
  data_date=$1
else
  data_date=`date -d "-1 days" +%F`
fi

DWD_PRODUCT_INC="
WITH
    t1 AS (
        SELECT
            log_id, user_id, product_id, sku_id, session_id, event_type, event_time, page_url,
            status, source_type, stay_time, seed, activity, device_type,
            ip_address, province, city, network_type, is_new_user, create_time, update_time
        FROM product_warehouse.dwd_product_info_full
        WHERE dt='${data_date}'
    ),
    t2 AS (
       SELECT
            product_id, product_name, category_id, brand_id, user_id, start_id, is_favorite, is_cart, product_price,
            price_level, zf_flag, product_status, sku_id, sku_name, sku_price, sku_original_price, category_name, level,
            category_status, brand_name, brand_desc, brand_country, brand_status, gender, age, register_time, last_login_time,
            user_level, content_type, view_count, create_time, update_time
        FROM product_warehouse.dim_product_info
        WHERE dt='${data_date}'
    ),
    t3 AS (
        SELECT
            review_id, product_id, user_id, sku_id, rating, create_time
        FROM product_warehouse.ods_product_review
        WHERE dt='${data_date}'
    )
INSERT OVERWRITE TABLE product_warehouse.dwd_product_inc PARTITION (dt='${data_date}')
SELECT
    t1.log_id,
    t1.user_id,
    t1.product_id,
    t1.sku_id,
    t2.sku_name,
    t1.session_id,
    t1.event_type,
    t1.event_time,
    t1.status,
    t1.source_type,
    t1.stay_time,
    t1.seed,
    t1.activity,
    t1.device_type,
    t1.ip_address,
    t1.province,
    t1.city,
    t1.network_type,
    t1.is_new_user,
    t2.product_name,
    t2.category_id,
    t2.category_name,
    t2.brand_id,
    t2.start_id,
    t2.is_favorite,
    t2.is_cart,
    t2.product_price,
    t2.price_level,
    t2.zf_flag,
    t2.product_status,
    t2.sku_price,
    t2.sku_original_price,
    t2.level,
    t2.category_status,
    t2.brand_name,
    t2.brand_desc,
    t2.brand_country,
    t2.brand_status,
    t2.gender,
    t2.age,
    t2.register_time,
    t2.last_login_time,
    t2.user_level,
    t2.content_type,
    t2.view_count,
    t3.rating,
    t1.create_time,
    t1.update_time
FROM t1
 JOIN t2 ON t1.product_id = t2.product_id
 JOIN t3 ON t1.user_id = t3.user_id;
"

/opt/module/spark/bin/beeline -u jdbc:hive2://node101:10001 -n bwie -e "${DWD_PRODUCT_INC}"